package com.example.tongyao.system.controller;

import com.example.tongyao.utils.QrCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import org.apache.logging.log4j.Logger;

/**
 * tongyao >>> 【com.example.tongyao.system.controller】
 * 二维码生成控制类
 *
 * @author: tongyao
 * @since: 2020-08-07 22:55
 */
@RestController
@Api(tags = "系统 - 二维码生成管理")
@RequestMapping("/system/sys-menu")
public class QrCodeController {

    //logger日志
    Logger logger = (Logger) LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);


    //获取配置文件里面的二维码url路径
    @Value("${qrCode.UrlAddress}")
    private String qrCodeUrlAddress;

    /**
     * 二维码生成
     * @param request
     * @param response
     * @param urlAddress 二维码地址
     */
    @ApiOperation(
            value = "二维码生成",
            notes = "二维码生成",
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "urlAddress",value = "二维码地址",required = true),
    })
    @GetMapping(value = "/add" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public void createQrCode(HttpServletRequest request, HttpServletResponse response,String urlAddress) {
        if(urlAddress == null){
            urlAddress = qrCodeUrlAddress;
        }

        StringBuffer url = request.getRequestURL();
        try {
            OutputStream os = response.getOutputStream();
            //requestUrl:需要生成二维码的连接，logoPath：内嵌图片的路径，os：响应输出流，needCompress:是否压缩内嵌的图片
            QrCodeUtils.encode(urlAddress, "http://www.baidu.com/test.jpg", os, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("二维码生成成功！");
    }
}